import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from '../router/index'
import { routesList } from '../stores/routesList'
// import { ElMessage } from 'element-plus' //Elmentui的提示信息

NProgress.configure({ showSpinner: false }) // 显示右上角螺旋加载提示
const whiteList: string[] = ['/login'] //定义白名单

// 路由守卫
router.beforeEach((to, from, next) => {
  const store = routesList()
  NProgress.start()
  if (localStorage.getItem('token')) {
    if (to.path === '/login') {
      next({ path: '/home' })
      NProgress.done()
    } else if (!to.name) {
      next({ path: '/404Page' })
      NProgress.done()
    } else {
      next()
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login`) // 否则全部重定向到登录页
      NProgress.done() //完成进度条
    }
  }
  store.$patch({
    routerName: to.path
  })
  if (sessionStorage.getItem('labels')) {
    store.$patch({
      labels: <any[]>JSON.parse(sessionStorage.getItem('labels') || '{}')
    })
  } else {
    if (!store.labels.length) {
      store.$patch({
        labels: <any[]>store.routesList.filter((item) => item.url == to.path)
      })
    }
  }
})
router.afterEach(() => {
  console.log('路由加载完成！')
  NProgress.done() //完成进度条
})
